package com.siwei.mes.service.impl;

import com.siwei.mes.common.util.DateHelper;
import com.siwei.mes.entity.Serial;
import com.siwei.mes.enums.GenerateCodeEnum;
import com.siwei.mes.mapper.SerialMapper;
import com.siwei.mes.service.SerialService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * (Serial)表服务实现类
 *
 * @author linzi
 * @since 2023-04-08 20:16:24
 */
@Service
public class SerialServiceImpl implements SerialService {
    @Resource
    private SerialMapper serialMapper;


    @Override
    public String genNo(String code) {
        String year = DateHelper.getYear() < 10 ? "0" + DateHelper.getYear() : DateHelper.getYear().toString();
        String month = DateHelper.getMonth() < 10 ? "0" + DateHelper.getMonth() : DateHelper.getMonth().toString();
        String day = DateHelper.getDay() < 10 ? "0" + DateHelper.getDay() : DateHelper.getDay().toString();
        Serial serial = serialMapper.selectBySerialNo(code);
        GenerateCodeEnum generateCodeEnum = GenerateCodeEnum.getName(code);
        String applyIdNumber = String.format(year.substring(2, 4) + month + day + "%03d", 0);
        if (serial == null) {
            serial = new Serial().setSerialNo(generateCodeEnum.getCode())
                    .setSerialNumber(applyIdNumber)
                    .setRemark(generateCodeEnum.getName());
            serialMapper.insertSelective(serial);
        } else {
            applyIdNumber = serial.getSerialNumber();
            int number = Integer.parseInt(applyIdNumber);
            applyIdNumber = String.valueOf(number + 1);
            serialMapper.updateByPrimaryKeySelective(serial.setSerialNumber(applyIdNumber).setRemark(generateCodeEnum.getName()));
        }
        return code + applyIdNumber;
    }
}
